﻿using System;
using System.Linq;
using System.Web;
using EPiBoost.Core.Helpers;
using EPiBoost.Core.Model;
using EPiServer.Core;
using EPiServer.Filters;

namespace EPiBoost.Core.Filters.PageFilters
{
    public class FilterPagination : IPageFilter
    {
		public string PageIndexQueryStringKey { get; set; }
		public string PageSizeQueryStringKey { get; set; }
		public int DefaultPageSize { get; set; }
		public Pagination PaginationLinks { get; set; }

    	public FilterPagination(int defaultPageSize = 10, string pageIndexQueryStringKey = "pg", string pageSizeQueryStringKey = "ps")
    	{
    		DefaultPageSize = defaultPageSize;
    		PageIndexQueryStringKey = pageIndexQueryStringKey;
    		PageSizeQueryStringKey = pageSizeQueryStringKey;
    	}


    	public void Filter(PageDataCollection pages)
    	{
			PaginationLinks = PaginationHelper.GetPaginationLinks(pages, DefaultPageSize, PageIndexQueryStringKey, PageSizeQueryStringKey);

    		int pageIndex;
    		int pageSize;
            if(PaginationHelper.TryGetValuesFromContext(PageIndexQueryStringKey, PageSizeQueryStringKey, DefaultPageSize, out pageIndex, out pageSize))
            {
            	int removeMax = Math.Min(pageIndex*pageSize, pages.Count);
				pages.RemoveRange(0, removeMax);
				while(pages.Count>pageSize){
					pages.RemoveAt(pages.Count-1);
				}
            }
    	}
		  

        public void Filter(object sender, FilterEventArgs e)
        {
            Filter(e.Pages);
        }

        public bool ShouldFilter(PageData page)
        {
            throw new NotImplementedException();
        }
    }
}
